<template>
  <el-select
    ref="selectRef"
    filterable
    collapse-tags
    v-model="state"
    class="width_100"
    :disabled="disabled"
    :multiple="multiple"
    collapse-tags-tooltip
    :clearable="clearable"
    :placeholder="placeholder"
    :filter-method="querySearch"
    @change="change"
    @focus="focus"
  >
    <el-option
      v-for="item in optionsList"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    ></el-option>
  </el-select>
</template>
<!-- 
  基础下拉筛选【全模糊查询】【关键字查询】【不区分大小写】
 -->
<script setup>
  /**
   * @props
   */

  const props = defineProps({
    // 值
    value: {
      type: String,
      default: "",
    },
    // 筛选
    options: {
      type: Array,
      default: [], // { value: '', label: '' } 格式限制
    },
    // 多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 清除
    clearable: {
      type: Boolean,
      default: true,
    },
    // 禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 提示
    placeholder: {
      type: String,
      default: "请选择",
    },
  });

  /**
   * @var
   */

  const state = ref("");
  const optionsList = toRef(props.options);
  const selectRef = ref();
  /**
   * @method
   */
  const emit = defineEmits(["change", "focus"]);

  // 全模糊
  const querySearch = (value) => {
    optionsList.value = props.options.filter((option) => {
      return (option?.label ?? "")
        ?.toLowerCase()
        .includes(value?.trim().toLowerCase());
    });
  };

  // 左模糊
  const querySearch1 = (queryString) => {
    const results = queryString
      ? props.options.filter(createFilter(queryString))
      : props.options;
    optionsList.value = results;
  };
  const createFilter = (queryString) => {
    return (restaurant) => {
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      );
    };
  };
  // change事件
  const change = (value) => {
    emit("change", value);
  };
  //focus事件
  const focus = (value) => {
    emit("focus");
  };

  watch(
    () => props.options,
    (newValue, oldValue) => {
      optionsList.value = newValue;
    },
    { deep: true }
  );
  defineExpose({
    selectRef,
  });
</script>

<style scoped></style>
